// Copyright (c) 2024, yuxinyong and contributors
// For license information, please see license.txt

frappe.ui.form.on("Freight Booking", {
	refresh(frm) {

	},
    upload_file: function(frm) {
        if (frm.is_new()) {
            frappe.msgprint('请先创建单据后再上传附件资料');
            return;
        }

        $('<input type="file" multiple accept=".pdf,.doc,.docx,.xls,.xlsx,.png,.jpg">').on('change', async function() {
            var files = this.files;
            var i = 0;

            async function uploadFile(file) {
                return new Promise(resolve => {
                    let reader = new FileReader();
                    reader.onload = function(e) {
                        var contents = e.target.result;
                        frappe.call({
                            method: 'zelin_agent_assistant.agent_assistant.doctype.freight_booking.freight_booking.upload_file',
                            args: {
                                docname: frm.docname,
                                doctype: frm.doctype,
                                filename: file.name,
                                filedata: contents
                            },
                            callback: function(response) {
                                console.log(response.message);
                                frm.reload_doc();
                                files_source = frm.doc.files
                                frappe.show_alert(__(file.name + '上传成功！'));
                                resolve(response.message);
                            }
                        });
                    };
                    reader.readAsDataURL(file);
                });
            }

            async function nextFile() {
                if (i >= files.length) {
                    frm.save();
                    return;
                }

                let file = files[i];

                try {
                    // 等待文件上传完成
                    let uploadResult = await uploadFile(file);
                    i++;
                    nextFile(); // 继续上传下一个文件
                } catch (error) {
                    console.error('File upload failed:', error);
                    i++;
                    nextFile(); // 继续上传下一个文件
                }
            }
            nextFile(); // 开始逐个上传文件
        }).click();
    }
});
